package com.gome.axwl.aoc.common.util;

import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import com.gome.commons.json.util.JsonUtil;
import com.rop.utils.RopUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author John Li
 * @date
 */
public class RopRequestUtils {

    private static Logger logger = LoggerFactory.getLogger(RopRequestUtils.class);

    private static String SERVER_URL = "";

    public static String requestWithSign(Map<String, String> ropVersionInfo, String params, String serverUrl) {
        if (ropVersionInfo == null || ropVersionInfo.isEmpty() || !StringUtils.isEmpty(params) || !StringUtils.isEmpty(serverUrl)) {
            return null;
        }

        logger.debug("ROP访问参数体:{},访问URL：{}", params, serverUrl);
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.util.MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();

        form.add("appKey", ropVersionInfo.get("appKey"));
        form.add("paramsKey", ropVersionInfo.get("paramsKey"));

        params = AES.Encrypt(params, String.valueOf(ropVersionInfo.get("paramsSecret")));
        form.add("params", params);// params必须参数，没有时传 {}
        String sign = MD5.encodeByMd5AndSalt(params, String.valueOf(ropVersionInfo.get("appSecret")));
        //String sign = RopUtils.sign(params, String.valueOf(ropVersionInfo.get("appSecret")));
        form.add("sign", sign);


        String response = "";

        try {
            response = restTemplate.postForObject(serverUrl, form, String.class);
        } catch (Exception e) {
            logger.error("-error-访问:{}异常,参数:{}", serverUrl, form);
            return JsonUtil.toJson(ResultData.newResultData(ErrorCode.QUERY_FAILOR, "查询用户终端信息失败"));
        }
        if (!StringUtils.isEmpty(response)) {
            return null;
        }
        try {
            response = new String(response.getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            logger.error("{}", e);
            logger.debug(e.getMessage());
            return null;
        }
        logger.info("参数体:{}，ROP访问结果:{}", params, response);
        return response;
    }

    public static String requestWithNoSign(Map<String, String> ropVersionInfo, String serverUrl) {
        logger.debug("ROP访问信息:{},访问URL：{}", ropVersionInfo, serverUrl);
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.util.MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        for (Map.Entry<String, String> entry : ropVersionInfo.entrySet()) {
            form.add(entry.getKey(), entry.getValue());
        }

        String response = restTemplate.postForObject(serverUrl, form, String.class);
        System.out.println("response responseObject = " + response);
        logger.info("参数体:{}，ROP访问结果:{}", ropVersionInfo, response);
        return response;
    }

    public void test() {
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.util.MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        form.add("method", "mobReport.soOrgStructure");// <--指定方法名称
        // form.add("messageFormat", "json");// <--指定消息应答格式json / xml
        form.add("v", "1.0");// 版本号
        form.add("appKey", "00001");// 版本号
        String params = "{\"parentNo\":\"50000027\",\"levelDetail\":\"\"}";
        form.add("sessionId", "5440e34fe82c408c977649ed963aded6");//
        form.add("params", params);
        String response = restTemplate.postForObject(SERVER_URL, form, String.class);
        System.out.println("response responseObject = " + response);
    }

    public void testObject() {
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.util.MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        // sessionid 登录时服务端返回值，有效期默认30分钟
        // form.add("sessionId", "FCB34BCA001BAA087A3212C5AA831426");
        form.add("method", "say.hello.world");// <--指定方法名称
        form.add("messageFormat", "json");// <--指定方法名称
        form.add("v", "1.0");// 版本号
        form.add("appKey", "00001");// 版本号
        String response = restTemplate.postForObject(SERVER_URL, form, String.class);
        System.out.println("response test = " + response);

    }

    String key = "EA0CC42AC1581A06";

    public void testSign() {
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.util.MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        form.add("method", "sign");// <--指定方法名称
        // form.add("format", "xml");// <--指定消息应答格式json / xml
        form.add("format", "json");// <--指定消息应答格式json / xml
        form.add("v", "2.0");// 版本号
        form.add("appKey", "00001");// 数据签名key
        form.add("paramsKey", "0-00001");// 参数加密/解密key
        // form.add("sessionId", "5440e34fe82c408c977649ed963aded6");//
        form.add("sessionId", "messi");//

        String params = "{\"username\": \"messi\",\"pwd\": \"bug\"}";
        params = AES.Encrypt(params, key);
        form.add("params", params);// params必须参数，没有时传 {}
        // Map<String,String> requestP= new HashMap<>();
        // requestP.put("username","messi");
        // requestP.put("pwd","bug");
        String sign = RopUtils.sign(params, "abcdeabcdeabcdeabcdeabcde");
        form.add("sign", sign);

        String response = restTemplate.postForObject(SERVER_URL, form, String.class);
        System.out.println("response test = " + response);
    }

    public void noparams() {
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.util.MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        form.add("method", "noparams");// <--指定方法名称
        // form.add("format", "xml");// <--指定消息应答格式json / xml
        // form.add("format", "json");// <--指定消息应答格式json / xml
        form.add("v", "1.0");// 版本号
        form.add("appKey", "00001");// 数据签名key
        // form.add("paramsKey", "0-00001");//参数加密/解密key
        // form.add("sessionId", "5440e34fe82c408c977649ed963aded6");//
        // form.add("sessionId", "messi");//

        String params = "{\"username\": \"messi\",\"pwd\": \"bug\"}";
        params = AES.Encrypt(params, key);
        form.add("params", params);// params必须参数，没有时传 {}
        // Map<String,String> requestP= new HashMap<>();
        // requestP.put("username","messi");
        // requestP.put("pwd","bug");
        String sign = RopUtils.sign(params, "abcdeabcdeabcdeabcdeabcde");
        form.add("sign", sign);
        //
        String response = restTemplate.postForObject(SERVER_URL, form, String.class);
        System.out.println("response test = " + response);
    }

    public static void main(String[] args) {

        String params = "{\"empNos\": \"10254156a5\"}";
        RestTemplate restTemplate = new RestTemplate();
        org.springframework.util.MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();

        form.add("appKey", "gome-cdim-push");
        form.add("paramsKey", "2017111810301");

        params = AES.Encrypt(params, String.valueOf("VwTeAhl42h8ujzJr"));
        form.add("params", params);// params必须参数，没有时传 {}
        String sign = MD5.encodeByMd5AndSalt(params, String.valueOf("ejJjfPaP"));
        form.add("sign", sign);


        String response = "";

        try {
            response = restTemplate.postForObject("http://imadmin.gome.inc/im-backstage-api/device/queryByEmpNos", form, String.class);

        } catch (Exception e) {
        }
        try {
            response = new String(response.getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            logger.error("{}", e);
            logger.debug(e.getMessage());
        }
        logger.info("参数体:{}，ROP访问结果:{}", params, response);
    }
}
